package com.sxbbc.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.api.common.ChickenMapping;
import com.sxbbc.api.service.IBusinessService;
import com.sxbbc.api.service.IOrderService;
import com.sxbbc.common.basics.files.RestUploadFileInfo;
import com.sxbbc.common.basics.files.UploadUtils;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.FarmLogisticsOrderDetailVo;
import com.sxbbc.common.core.dto.jz.FarmLogisticsOrderOutVo;
import com.sxbbc.common.core.dto.jz.FarmOrderOutVo;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.service.impl.CCustomerServiceImpl;
import com.sxbbc.common.core.service.system.login.LoginTokenService;
import com.sxbbc.common.core.utils.BasePage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 *
 * </p>
 *
 * @author zhangq
 * @since 2020/3/31
 */
@RestController

public class ChickenController {

    @Autowired
    private IChickenSubscribeService iChickenSubscribeService;
    @Autowired
    private IChickenLogisticsOrderService iChickenLogisticsOrderService;
    @Autowired
    private IOrderExpDetailService iOrderExpDetailService;
    @Autowired
    private IChickenCouponService iChickenCouponService;
    @Autowired
    private IChickenOrderService iChickenOrderService;
    @Autowired
    private ICCustomerService icCustomerService;
    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private LoginTokenService loginTokenService;
    @Autowired
    private CCustomerServiceImpl cCustomerService;
    @Autowired
    private IChickenLevelService iChickenLevelService;
    @Autowired
    private IOrderMainService iOrderMainService;
    @Autowired
    private IBusinessService iBusinessService;

    //region 鸡舍信息

    /**
     * 查询鸡舍等级列表
     *
     * @param page
     * @return
     */
    @RequestMapping(value = ChickenMapping.CR_HANDLE_SELECT)
    @ResponseBody
    public RestResponse handleSelectChickenRepository(BasePage<ChickenLevel> page, String token) {
        QueryWrapper<ChickenLevel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", StaticUtils.STATUS_YES)
                .orderByAsc("level");
        IPage<ChickenLevel> pageInfo = iChickenLevelService.page(page, queryWrapper);
        for (ChickenLevel record : pageInfo.getRecords()) {
            record.setRemark(record.getTitle());
            record.setSurplusQty(record.getTotalQty()-record.getSaleQty());
        }
        return GetRest.getSuccess("", pageInfo);
    }

    /**
     * 查询单个鸡舍等级信息
     *
     * @param id
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CR_HANDLE_GET)
    @ResponseBody
    public RestResponse handleGetChickenRepository(Integer id, String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        ChickenLevel repository = iChickenLevelService.getById(id);
        return GetRest.getSuccess("", repository);
    }

    //endregion

    //region 提鸡券管理

    /**
     * 查询提鸡券列表
     *
     * @param page
     * @param
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CC_HANDLE_SELECT)
    public RestResponse handleSelectChickenCoupon(BasePage<ChickenCoupon> page, ChickenCoupon chickenCoupon, String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        chickenCoupon.setCid(cid);
        IPage<ChickenCoupon> pageInfo = iChickenCouponService.selectChickenCouponList(page, chickenCoupon);
        return GetRest.getSuccess("", pageInfo);
    }

    /**
     * 查询提鸡券角标
     *
     * @param chickenCoupon
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CC_HANDLE_STATUSNUM)
    public RestResponse handleGetChickenCouponNum(ChickenCoupon chickenCoupon, String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        chickenCoupon.setCid(cid);
        Map<String, Integer> map = iChickenCouponService.getCouponNum(chickenCoupon);
        return GetRest.getSuccess("", map);
    }

    /**
     * 查询单个提鸡券
     *
     * @param id
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CC_HANDLE_GET)
    public RestResponse handleGetChickenCoupon(Integer id, String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        ChickenCoupon chickenCoupon = iChickenCouponService.getById(id);
        return GetRest.getSuccess("", chickenCoupon);
    }

    /**
     * 查询有效可转赠提鸡券
     *
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CC_HANDLE_SELECT_EFFECTIVE)
    public RestResponse handleSelectEffectiveChickenCoupon(String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        QueryWrapper<ChickenCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cid", cid)
                .eq("status", ChickenCouponStatusEnums.WAITUSE.getId());
        List<ChickenCoupon> couponList = iChickenCouponService.list(queryWrapper);
        return GetRest.getSuccess("", couponList);
    }

    /**
     * 转赠提鸡券
     *
     * @param ids
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CC_HANDLE_GIVING)
    public RestResponse handleGetChickenCouponNum(String targetPhone, @RequestParam(value = "ids") List<Integer> ids, String token) {
        try {
            Integer cid = loginTokenService.validLoginCid(token);
            if (StringUtils.isBlank(token) || cid == null) {
                return GetRest.getFail("获取用户信息失败");
            }
            //当前用户
            CCustomer currentCustomer = cCustomerService.getById(cid);

            QueryWrapper<CCustomer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", targetPhone);
            CCustomer targetCustomer = cCustomerService.getOne(queryWrapper);
            if (targetCustomer == null) {
                return GetRest.getFail("对方账号不存在");
            }
            if (CalcuUtils.getInstance().isEquals(targetCustomer.getId(), cid)) {
                return GetRest.getFail("不能转赠给自己");
            }
            QueryWrapper<ChickenCoupon> couponQueryWrapper = new QueryWrapper<>();
            couponQueryWrapper.in("id", ids);
            List<ChickenCoupon> couponList = iChickenCouponService.list(couponQueryWrapper);
            if (couponList.size() == 0) {
                return GetRest.getFail("提鸡券不存在");
            }
            CalcuUtils calc = CalcuUtils.getInstance();
            for (ChickenCoupon chickenCoupon : couponList) {
                if (chickenCoupon.getStatus() != ChickenCouponStatusEnums.WAITUSE.getId()) {
                    return GetRest.getFail("选择的提鸡券有处于不可转赠状态");
                }
                if (chickenCoupon.getStatus() == ChickenCouponStatusEnums.GIVING.getId()) {
                    return GetRest.getFail("选择的提鸡券有已转赠状态，不可重复转赠");
                }
            }

            UpdateWrapper<ChickenCoupon> updateWrapper = new UpdateWrapper<>();
            updateWrapper.in("id", ids);

            ChickenCoupon coupon = new ChickenCoupon();
            coupon.setTargetCid(targetCustomer.getId());
            coupon.setStatus(ChickenCouponStatusEnums.GIVING.getId());
            // coupon.setGivingTime(new Date());

            boolean updated = iChickenCouponService.update(coupon, updateWrapper);
            if (!updated) {
                return GetRest.getFail("操作失败");
            }

            List<ChickenCoupon> addCouponList = new ArrayList<>();
            for (ChickenCoupon item : couponList) {
                //新增转赠优惠券
                ChickenCoupon addCoupon = new ChickenCoupon();
                BeanUtils.copyProperties(item, addCoupon);
                addCoupon.setOrderNo(CalcuUtils.getInstance().getOrderCode("COG"));
                addCoupon.setOrderCode(item.getOrderCode());
                addCoupon.setCid(targetCustomer.getId());
                addCoupon.setSource("用户【" + currentCustomer.getNickName() + "】转赠");
                addCoupon.setStatus(ChickenCouponStatusEnums.WAITUSE.getId());
                addCoupon.setTargetCid(null);
                addCoupon.setGivingTime(null);
                //addCoupon.setCreateTime(new Date());
                addCouponList.add(addCoupon);
            }
            boolean saved = iChickenCouponService.saveBatch(addCouponList);
            if (!saved) {
                return GetRest.getFail("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return GetRest.getSuccess("", "操作成功");
    }

    //endregion

    //region 挂售 & 领取

    /**
     * 查询挂售/领取订单
     *
     * @param token
     * @param page
     * @param chickenOrder
     * @return
     */
    @RequestMapping(value = ChickenMapping.CO_HANDLE_SELECT)
    public RestResponse handleSelectChickenOrder(String token, BasePage<ChickenOrder> page, ChickenOrder chickenOrder) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        chickenOrder.setCid(cid);
        IPage<FarmOrderOutVo> chickenOrderList = iChickenOrderService.selectChickenOrderList(page, chickenOrder);
        return GetRest.getSuccess("", chickenOrderList);
    }

    //endregion

    //region 预约提鸡

    /**
     * 查询可预约提鸡时间
     *
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CS_HANDLE_SUBSCRIBE_TIME)
    public RestResponse handleSubscribeTime(String token, Integer bid) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        BBusiness bBusiness = iBusinessService.getById(bid);
        if (bBusiness == null) {
            return GetRest.getFail("获取店铺信息失败");
        }
        if (!CalcuUtils.getInstance().isEquals(bBusiness.getBType(), BusinessTypeEnums.OWN_BUSINESS.getId())) {
            return GetRest.getFail("该店铺不是自营店铺无法进行预约提鸡");
        }

        List<Map<String, String>> times = new ArrayList<>();
        Calendar c_begin = Calendar.getInstance();
        Calendar c_end = Calendar.getInstance();
        DateFormatSymbols dfs = new DateFormatSymbols();
        String[] weeks = dfs.getWeekdays();
        c_begin.set(Calendar.DAY_OF_MONTH, c_begin.get(Calendar.DAY_OF_MONTH) + 1);
        c_end.set(Calendar.DAY_OF_MONTH, c_end.get(Calendar.DAY_OF_MONTH) + 7);

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat simpleDateFormat = new SimpleDateFormat("MM.dd");
        int count = 1;
        while (c_begin.before(c_end)) {
            HashMap<String, String> map = new HashMap<>();
            String displaytext = weeks[c_begin.get(Calendar.DAY_OF_WEEK)].replace("星期", "周");
            switch (displaytext) {
                case "Saturday":
                    displaytext = "周六";
                    break;
                case "Sunday":
                    displaytext = "周日";
                    break;
                case "Monday":
                    displaytext = "周一";
                    break;
                case "Tuesday":
                    displaytext = "周二";
                    break;
                case "Wednesday":
                    displaytext = "周三";
                    break;
                case "Thursday":
                    displaytext = "周四";
                    break;
                case "Friday":
                    displaytext = "周五";
                    break;
            }
            if (count == 1) {
                displaytext = "明天";
            }
            map.put("text", displaytext);
            map.put("datetime", dateFormat.format(c_begin.getTimeInMillis()));
            map.put("value", simpleDateFormat.format(c_begin.getTimeInMillis()));
            times.add(map);
            System.out.println("日期：" + dateFormat.format(c_begin.getTimeInMillis()) + ","
                    + displaytext);
            c_begin.add(Calendar.DAY_OF_YEAR, 1);
            count++;
        }
        return GetRest.getSuccess("", times);
    }

    /**
     * 生成预约提鸡记录
     *
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CS_HANDLE_SUBSCRIBE_APPLY)
    public RestResponse handleSubscribeApply(@RequestParam("ids") List<Integer> ids, Integer bid, @RequestParam("subscribeTime") LocalDateTime subscribeTime, String token) {
        try {
            Integer cid = loginTokenService.validLoginCid(token);
            if (StringUtils.isBlank(token) || cid == null) {
                return GetRest.getFail("获取用户信息失败");
            }
            QueryWrapper<ChickenCoupon> couponQueryWrapper = new QueryWrapper<>();
            couponQueryWrapper.in("id", ids).eq("cid", cid).eq("status", ChickenCouponStatusEnums.WAITUSE.getId());
            List<ChickenCoupon> couponList = iChickenCouponService.list(couponQueryWrapper);

            CalcuUtils calc = CalcuUtils.getInstance();
            //TODO 图片上传
            if (couponList.size() == 0) {
                return GetRest.getFail("提鸡券不存在");
            } else if (!calc.isEquals(couponList.size(), ids.size())) {
                return GetRest.getFail("选择提鸡券中存在无效券，请重新选择");
            }

            String orderCode = calc.getOrderCode("CS");
            RestUploadFileInfo uploadQr = new UploadUtils().uploadQr(orderCode);
            if (uploadQr.isStatus()) {
                //新增提鸡预约记录
                ChickenSubscribe chickenSubscribe = new ChickenSubscribe();
                chickenSubscribe.setCcids(StringUtils.join(ids.toArray(), ","));
                chickenSubscribe.setOrderCode(orderCode);
                chickenSubscribe.setBid(bid);
                chickenSubscribe.setCid(cid);
                chickenSubscribe.setSubscribeTime(subscribeTime);
                chickenSubscribe.setNo(calc.getOrderCode("CS"));
                chickenSubscribe.setInvalidTime(subscribeTime.plusDays(30));
                chickenSubscribe.setNum(ids.size());
                chickenSubscribe.setSubscribeCode(uploadQr.getData());
                boolean saved = iChickenSubscribeService.save(chickenSubscribe);
                if (saved) {
                    //更新提鸡券状态
                    QueryWrapper<ChickenCoupon> queryWrapper = new QueryWrapper<>();
                    queryWrapper.in("id", ids);

                    ChickenCoupon chickenCoupon = new ChickenCoupon();
                    chickenCoupon.setStatus(ChickenCouponStatusEnums.WAITCONFIRM.getId());
                    chickenCoupon.setUseType(ChickenCouponUseTypeEnums.OWN.getId());
                    chickenCoupon.setUseTime(new Date());
                    iChickenCouponService.update(chickenCoupon, queryWrapper);
                }
            }
        } catch (Exception e) {
            return GetRest.getFail("", "预约失败,你可以重新预约看看...");
        }
        return GetRest.getSuccess("", "操作成功");
    }

    /**
     * 查询预约提鸡订单
     *
     * @param
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CS_HANDLE_SUBSCRIBE_ORDER)
    public RestResponse handleSelectSubscribeOrderList(String token, BasePage<ChickenSubscribe> page, ChickenSubscribe chickenSubscribe) {

        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        chickenSubscribe.setCid(cid);
        IPage<ChickenSubscribe> pageInfo = iChickenSubscribeService.selectChickenSubscribeList(page, chickenSubscribe);
        return GetRest.getSuccess("", pageInfo);
    }

    /**
     * 查询核销码信息
     *
     * @param id
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CS_HANDLE_SUBSCRIBE_STATUS)
    public RestResponse handleSubscribeApply(Integer id, String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        ChickenSubscribe chickenSubscribe = iChickenSubscribeService.getById(id);
        return GetRest.getSuccess("", chickenSubscribe);
    }

//    /**
//     * 核销预约提鸡
//     *
//     * @param orderCode
//     * @param token
//     * @return
//     */
//    @RequestMapping(value = ChickenMapping.CS_HANDLE_SUBSCRIBE_CODE)
//    public RestResponse handleSubscribeCode(String orderCode, String token) {
//        Integer cid = loginTokenService.validLoginCid(token);
//        if (StringUtils.isBlank(token) || cid == null) {
//            return GetRest.getFail("获取用户信息失败");
//        }
//
//        QueryWrapper<ChickenSubscribe> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("cid", cid).eq("order_code", orderCode);
//        ChickenSubscribe chickenSubscribe = iChickenSubscribeService.getOne(queryWrapper);
//        CalcuUtils calcuUtils = CalcuUtils.getInstance();
//        if (calcuUtils.isEquals(chickenSubscribe.getStatus(), ChickenSubscribeStatusEnums.SUBSCRIBE.getId())) {
//            chickenSubscribe.setStatus(ChickenSubscribeStatusEnums.USED.getId());
//            chickenSubscribe.setSubscribeTime(LocalDateTime.now());
//            iChickenSubscribeService.updateById(chickenSubscribe);
//            return GetRest.getSuccess("", "核销成功");
//        }
//        return GetRest.getFail("操作失败");
//    }

    //endregion

    //region 物流提鸡

    /**
     * 物流提鸡 支付页面显示
     *
     * @param
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CL_HANDLE_GET_PAYINFO)
    public RestResponse handleSelectDetail(Integer id, Integer addrid, String token) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        return iChickenLogisticsOrderService.getChickenLogisticsPayInfo(id, cid, addrid);
    }

    /**
     * 物流提鸡订单查询
     *
     * @param token
     * @param page
     * @param orderMain
     * @return
     */
    @RequestMapping(value = ChickenMapping.CL_HANDLE_SELECT)
    public RestResponse selectChickenLogisticsOrderList(String token, BasePage<OrderMain> page, OrderMain orderMain) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        orderMain.setCid(cid);
        IPage<FarmLogisticsOrderOutVo> chickenOrderList = iOrderMainService.selectChickenLogisticsOrderList(page, orderMain);
        return GetRest.getSuccess("", chickenOrderList);
    }

    /**
     * 物流提鸡订单详情
     *
     * @param token
     * @return
     */
    @RequestMapping(value = ChickenMapping.CL_HANDLE_GET)
    public RestResponse selectChickenLogisticsOrderDetail(String token, String orderCode) {
        Integer cid = loginTokenService.validLoginCid(token);
        if (StringUtils.isBlank(token) || cid == null) {
            return GetRest.getFail("获取用户信息失败");
        }
        OrderMain order = iOrderMainService.getByOrderCode(orderCode);
        if (!CalcuUtils.getInstance().isEquals(cid, order.getCid())) {
            return GetRest.getFail("订单数据有误");
        }
        FarmLogisticsOrderDetailVo result = iOrderService.handleQueryChickenLogisticsOrderDetailById(order.getId());
        return GetRest.getSuccess("", result);
    }

    //endregion
}
